# -*- coding: utf-8 -*-
import json
import re
import string

from config.cate import get_product_cate
from db.mysql import connect_to_db


class Product:
    cate_id:int = 0
    new_cate_id:int = 0
    new_cate_name: string = ''
    row = None
    rows = None
    conn = None
    product_id:int = 0
    id:int = 0
    cdn_url:str = "https://imgl.lily-bearing.com"
    def __init__(self, new_cate_id:int = 0):
        self.new_cate_id = new_cate_id
        category = get_product_cate()
        if self.new_cate_id in category:
            self.new_cate_name = str(category[self.new_cate_id]['name'])
            self.cate_id = int(category[self.new_cate_id]['lily_id'])
        self.conn = connect_to_db('192.168.0.10','root','123456')
    def add(self):
        """
        同步产品入口
        :return:boolean
        """
        if self.cate_id <= 0 or self.new_cate_name =='':
            return False
        try:
            while True:
                if self.__get_old_product() and not self.row:
                    break
                else:
                    if not self.__add_new_product() or not self.__get_old_product_detail():
                        self.id = self.id + 1
                    else:
                        self.__add_new_product_detail()
                        self.id=self.row[0]
        finally:
            if self.conn:
                self.conn.close()
        return True


    def __get_old_product(self):
        """
        获取lily产品列表
        :return:boolean
        """
        cursor=self.conn.cursor()
        sql = "select * from lilynew.lily_products where class_id=%s and id>%s order by id asc limit 1"
        cursor.execute(sql, (self.cate_id, self.id,))
        self.row = cursor.fetchone()
        cursor.close()
        return True

    def __add_new_product(self):
        cursor=self.conn.cursor()
        sql = "insert into bearing_web.t_product(cate_id,name,thumb,pdf,price) values (%s,%s,%s,%s,%s)"
        pdf = self.cdn_url
        if self.row[13] is not None:
            pdf = pdf + self.row[13]
        thumb = self.cdn_url
        if self.row[11] is not None:
            thumb = thumb + self.row[11]
        cursor.execute(sql,(self.new_cate_id,self.row[5],thumb,pdf,self.row[7],))
        self.conn.commit()
        self.product_id=cursor.lastrowid
        cursor.close()
        return True

    def __get_old_product_detail(self):
        cursor=self.conn.cursor()
        sql = "select * from lilynew.lily_products_detail where class_id=%s and pid=%s order by id asc"
        cursor.execute(sql, (self.cate_id, self.row[0],))
        self.rows = cursor.fetchall()
        cursor.close()
        return True

    def __add_new_product_detail(self):
        attr = {}
        for row in self.rows:
            key = row[3].replace('（','(').replace('）',')')
            # 提取括号内容作为单位
            match = re.search(r'\((.*?)\)',key)
            if match:
                unit = match.group(1)
            else:
                unit = ''
            # 去除括号内容
            key = key.replace('(' + unit + ')', '').strip().replace(' ', '_').lower()
            if key not in attr:
                attr[key]=[]
            attr[key].append({
                'alias':row[4] if row[4] is not None else '',
                'value':row[5],
                'is_show':row[13],
                'sort':row[14],
                'unit':unit
            })

        # 增加分类以及分类属性值
        attr['cate_id']=self.new_cate_id
        attr['bearing_type'] = self.new_cate_name
        attr['product_id'] = self.product_id
        attr['product_no'] = self.row[5]

        cursor=self.conn.cursor()
        sql = "insert into bearing_web.t_product_detail (product_id,cate_id,attr) values (%s,%s,%s)"
        cursor.execute(sql,(self.product_id,self.new_cate_id,json.dumps(attr),))
        self.conn.commit()
        cursor.close()
        return True